//定位显示
var arrayLiFtp = [];
var arrayLiIndFtp = 0;

var ftpRouteChanged = false;

var deleteHostIds ="";

var isFtpTest = false;
$(document).ready(function() {
	
	
		/* 系统树 */
		$('#system_selectionFtp').window({
			width:310,
			height:355,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false,
			onClose: function () {
				$("#ttFtp").html("");
			}
		});
		$('#system_selectionFtp').window('close');  //关闭窗口
	
		$('#winFtp').window('close');
      // Initialize Smart Wizard
  		$('#wizardFtp').smartWizard({
  		  // Properties
  		    selected: 0,  // Selected Step, 0 = first step   
  		    keyNavigation: false, // Enable/Disable key navigation(left and right keys are used if enabled)
  		    enableAllSteps: true,  // Enable/Disable all steps on first load
  		    transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft
  		    contentURL:null, // specifying content url enables ajax content loading
  		    contentCache:true, // cache step contents, if false content is fetched always from ajax url
  		    cycleSteps: false, // cycle step navigation
  		    enableFinishButton: false, // makes finish button enabled always
  		    errorSteps:[],    // array of step numbers to highlighting as error steps
  		    labelNext:'下一步', // label for Next button
  		    labelPrevious:'上一步', // label for Previous button
  		    labelFinish:'提交',  // label for Finish button        
  		  // Events
  		    onLeaveStep: onLeaveStepCallBackFtp, // triggers when leaving a step
  		    onShowStep: onShowStepCallBackFtp,  // triggers when showing a step
  		    onFinish: onFinishCallBackFtp  // triggers when Finish button is clicked
  		 });
  		
  		 
  		
  		$('#comboxFieldNameFtp').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	var FieldName = $('#comboxFieldNameFtp').combobox('getData');
		    	$("#comboxFieldNameFtp").combobox('setValue',FieldName[0].id);
		    },	
		    onSelect: function(record){
		    	comboxSystemNameFtp.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	comboxSystemNameFtp.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	var SystemName = $('#comboxSystemNameFtp').combobox('getData');
        				$("#comboxSystemNameFtp").combobox('setValue',SystemName[0].id);
        		    }
                }).load();
		    }
		    
		});
		
		
		var comboxSystemNameFtp = $('#comboxSystemNameFtp').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
		
		
		$('#comboxIsPublicFtp').combobox({
			url: BASE_URL_DATA_DICTIONARY_VALUE_SEARCH +'/findByTypeCode?typeCode='+DDTC_IS_PUBLIC + '&v=' + Math.random(),
			valueField: 'valueCode',
		    textField: 'valueName',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	return data;
		    },
		    onLoadSuccess:function(){
		    	var isPublic = $('#comboxIsPublicFtp').combobox('getData');
		    	$("#comboxIsPublicFtp").combobox('setValue',isPublic[0].valueCode);
		    	
		    	var chooseVal = $("#comboxIsPublicFtp").combobox('getValue');
		    	if(chooseVal=="0"){
		    		$("#li_visibleFtp").css("display","block");
		    	}else{
		    		$("#li_visibleFtp").css("display","none");
		    	}
		    	
		    },
		    onSelect: function(record){
		    	var chooseVal = $("#comboxIsPublicFtp").combobox('getValue');
		    	if(chooseVal=="0"){
		    		$("#li_visibleFtp").css("display","block");
		    	}else{
		    		$("#li_visibleFtp").css("display","none");
		    	}
		    }
		});
		
		$('#comboxExecutionCycleTime').combobox({
			url: BASE_URL_DATA_DICTIONARY_VALUE_SEARCH +'/findByTypeCode?typeCode='+DDTC_KETTLE_JOB_SCHEDULE_CYCLE_UNIT + '&v=' + Math.random(),
			valueField: 'valueCode',
		    textField: 'valueName',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	return data;
		    },
		    onChange:function(e){
		    	var chooseVal = $("#comboxExecutionCycleTime").combobox('getValue');
				var cycleNum = $('#txtExecutionCycleNumber').val();
				if(chooseVal == "5" && cycleNum == "1")
				{
					$(".daySel, .txtEvery, .text_tips, #end_time_li").show();
				}else if(chooseVal == "1")
				{
					$(".txtEvery, .daySel, .text_tips, #end_time_li").hide();
				}else
				{
					$(".txtEvery, .text_tips, #end_time_li").show();
					$(".daySel").hide();
				}
				$('#limitFormFtp').data('changed',true); 
		    },
		    onLoadSuccess:function(){
		    	var cycleTimeData = $('#comboxExecutionCycleTime').combobox('getData');
				$("#comboxExecutionCycleTime").combobox('setValue',cycleTimeData[4].valueCode);
		    }
		    
		});
		
		$('#txtExecutionCycleNumber').bind('input propertychange', function() {
			var chooseVal = $("#comboxExecutionCycleTime").combobox('getValue');
			var cycleNum = $('#txtExecutionCycleNumber').val();
	    	if(chooseVal == "5" && cycleNum == "1")
			{
				$(".daySel").show();
			}else{
				$(".daySel").hide();
			}
		});
		
		//源主机所属领域
		$("#sourceFieldSet_1 .sourceComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	/*var FieldName = $("#sourceFieldSet_1 .sourceComboxFieldName").combobox('getData');
		    	$("#sourceFieldSet_1 .sourceComboxFieldName").combobox('setValue',FieldName[0].id);*/
		    },	
		    onSelect: function(record){
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	/*var SystemName = $("#sourceFieldSet_1 .sourceComboxSystemName").combobox('getData');
        		    	$("#sourceFieldSet_1 .sourceComboxSystemName").combobox('setValue',SystemName[0].id);*/
        		    }
                }).load();
		    }
		    
		});
		
		//源主机所属系统
		var sourceComboxSystemName = $("#sourceFieldSet_1 .sourceComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
		
		//目标主机所属领域
		$("#desFieldSet_1 .desComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	/*var FieldName = $("#desFieldSet_1 .desComboxFieldName").combobox('getData');
		    	$("#desFieldSet_1 .desComboxFieldName").combobox('setValue',FieldName[0].id);*/
		    },	
		    onSelect: function(record){
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	/*var SystemName = $("#desFieldSet_1 .desComboxSystemName").combobox('getData');
        		    	$("#desFieldSet_1 .desComboxSystemName").combobox('setValue',SystemName[0].id);*/
        		    }
                }).load();
		    }
		    
		});
		
		
		//目标主机所属系统
		var desComboxSystemName = $("#desFieldSet_1 .desComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
	  	function onLeaveStepCallBackFtp(obj, context){
	  		isFtpTest = false;
	  		var step_num= obj.attr('rel'); // get the current step number
	  		/*验证表单数据是否正确*/
	  		if(context.fromStep < context.toStep){
		  		if(step_num == 1){
		  			if(!$("#basicInfoFormFtp").form("validate")){
		  				return false;
		  			}
		  		}else if(step_num == 2){
		  			var sourceDatas = getSourceDatas();
					if(sourceDatas == false){
						return false;
					}
		  		}else if(step_num == 3){
		  			var desDatas = getDesDatas();
					if(desDatas == false){
						return false;
					}
		  		}else if(step_num == 4){
		  			/*var packageJarNameFtp = $.trim($("#packageJarNameFtp").val());
					if(packageJarNameFtp != "")
					{
					}else
					{
						$.messager.alert('警告', '<p>接口部署包不能为空!</p>', 'warning');
						return false;
					}*/
		  		}
	  		}
	  		return true;
	  		
	  	}
	  	
	  	function onShowStepCallBackFtp(obj){
	  		var step_num= obj.attr('rel');
	  		if(step_num == 1){
	  			//alert("onShowStepCallBack" + step_num);
	  		}else if(step_num == 2){
	  			//alert("onShowStepCallBack" + step_num);
	  		}else if(step_num == 3){
	  			//alert("onShowStepCallBack" + step_num);
	  		}else{
	  			//alert("onShowStepCallBack" + step_num);
	  		}
	  		
	  	}
	  	
	  	function onFinishCallBackFtp(){
	  		isFtpTest = false;
	  		var result = getFormDatasFtp();
	  		if(result == false){
	  			return;
	  		} 
	  		var interfaceDatas = getFormDatasFtp();
	  		var jsonData = {
				  	interfaceDatas:interfaceDatas
				};
	  		if($("#basicInfoFormFtp").form("validate")){
	  			$("#progressbar3, #progressbar_tips3").fadeIn();
	  			loading_point.timer = setInterval(loading3,200);
		  		$.ajax({
		  			type: "post",
		  			url: BASE_URL_HTTP_INTERFACE + '/ftpServiceUpdate' + '?v=' + Math.random(),
		  			dataType:'json',
		  			data: JSON.stringify(jsonData),
		  			contentType:"application/json",
		  			success: function(result) {
		  				$("#progressbar3, #progressbar_tips3").fadeOut();
	  					clearInterval(loading_point.timer);
		  				//alert("result" + result.backValue);
		  				if(result.backValue == true){
		  					$.messager.alert('提示','<p>修改成功</p>','info',function(){
		  						$('#winFtp').window('close');
		  						$("#datagrid").datagrid("reload");
		  					});
		  				}else if(result.backValue == false){
		  					$.messager.alert('错误','<p>修改失败，' + result.errorDes + '</p>','error',function(){
		  					});
		  				}
		  			},
		  			error: function() {
		  				$("#progressbar3, #progressbar_tips3").fadeOut();
	  					clearInterval(loading_point.timer);
		  				$.messager.alert('错误','<p>服务异常，修改失败，请稍后重试或联系管理员!</p>', 'error');
		  			}
		  		});
	  		}
	  		
	  	}
		
	  	
	  	
		
		/* 可见范围 */
		$("#selSystemBtnFtp").click(function(e) {
			//if(treeData==null){
				$("#ttFtp").tree({
					url:BASE_URL_TREE + '/getFieldSystemsForEasyUiTree' + '?v=' + Math.random(),
					method: "get",
					lines:false,
					async:false,
					checkbox: true,
					loadFilter: function(data,parent) {
						treeData = [{text:"全部", children:data, nodeType:"root"}];
						//alert(JSON.stringify(treeData));
						return treeData;
					},
					onLoadSuccess:function()
					{
						$("#ttFtp > li > ul > li > ul > li > .tree-node > .tree-file").css("background","url('../../../images/st_folder.png') no-repeat 2px 2px");
						$("#ttFtp > li > ul > li > .tree-node > .tree-file").parent().parent().css("display","none");
						reSetTreeFtp();
					},
					onClick:function(node){
						if(node.checked)
						{
							$("#ttFtp").tree("uncheck", node.target);
						}
						else
						{
							$("#ttFtp").tree("check", node.target);
						}
						
						//$("#systemName").val(node.text);
						//choose_tree();
					}
				});
			//}else{
				//reSetTree()
			//}
			
			
			return false;
		});
		
		$("#ensureSelectFtp").click(function (e) {
			var checkedNodes = $("#ttFtp").tree("getChecked");
			var selectSystems = "";
			var systemsName = "";
			for(var i = 0, len = checkedNodes.length; i < len; ++i)
			{
				var tempNode = checkedNodes[i];
				if(tempNode.nodeType != "fieldSystem")
				{
					continue;
				}
				selectSystems += (selectSystems != ""? ",":"") + tempNode.id;
				systemsName += (systemsName != ""? ",":"") + tempNode.text;
			}
			$("#strFieldSystemsFtp").val(selectSystems);
			$("#systemFtp").val(systemsName);
			$('#system_selectionFtp').window('close');	
		});
		
		
		$("#searchNodeFtp").click(function (e) { 
			if($("#systemNameFtp").val() != '')
			{
				choose_treeFtp();
			}
			else
			{
				$("#systemNameFtp").val("");//将。改为#
				var row = $('#ttFtp li .tree-node');  
				row.removeClass('tree-node-selected');
				$(".tree_conFtp").scrollTop(0);
			}
		});
		
		$("#systemNameFtp").bind('input propertychange', function() {
			arrayLiFtp = [];
			arrayLiIndFtp = 0;
			if($("#systemNameFtp").val() != '')
			{
				choose_treeFtp();
			}else
			{
				$("#ff input").val("");
				var row = $('#ttFtp li .tree-node');  
				row.removeClass('tree-node-selected');
				$(".tree_conFtp").scrollTop(0);
			}
		});
		
		$(document , "#systemNameFtp").keyup(function(event){
		  if(event.keyCode == 8){
		    $("#searchNodeFtp").trigger("click");
		  }
		});
		$(document , "#systemNameFtp").keyup(function(event){
		  if(event.keyCode ==13){
		    $("#searchNodeFtp").trigger("click");
		  }
		});
		
		/* 可见范围 */
		
		
		$("#sourceHostFormFtp :input").change(function (){
			$('#sourceHostFormFtp').data('changed',true); 
		});
		
		$("#desHostFormFtp :input").change(function (){
			$('#desHostFormFtp').data('changed',true); 
		});
		
		$("#limitFormFtp :input").change(function (){
			$('#limitFormFtp').data('changed',true); 
		});
		
		
		//$("#sourceHostFormFtp :input").change(function (){ $('#sourceHostFormFtp').data('changed',true); });
			
  	}); 
  
	
	//获取所有表单数据
	var interfaceDatasFtp;
	function getFormDatasFtp(){
			var row = $('#datagrid').datagrid('getSelected');
			//alert(row.type + row.bundleType);
			var id = row.interfaceId;
			var sourceDatas = getSourceDatas();
			if(sourceDatas == false){
				return false;
			}
			var desDatas = getDesDatas();
			if(desDatas == false){
				return false;
			}
			
			//判断表单是否发生改变
			if($('#sourceHostFormFtp').data('changed') || $('#desHostFormFtp').data('changed') || $('#limitFormFtp').data('changed')){
				ftpRouteChanged = true;
			}else{
				ftpRouteChanged = false;
			}
				
			var interfaceName = $.trim($("#interfaceNameFtp").val());
			var interfaceCode = $("#interfaceCodeFtp").val();
			var fieldId = $("#comboxFieldNameFtp").combobox("getValue");
			var systemId = $("#comboxSystemNameFtp").combobox("getValue");
			var interfaceVersion = $.trim($("#interfaceVserionFtp").val());
			var interfaceDes = $.trim($("#interfaceDescriptionsFtp").val());
  			var overTimeSetting = $.trim($("#overTimeSettingFtp").val());
  			var isPublic = $("#comboxIsPublicFtp").combobox("getValue");
  			
  			var ifScheduleId = $("#ifScheduleId").val();
  			var runWay = $("#comboxExecutionCycleTime").combobox('getValue');
  			var runCyc = $("#txtExecutionCycleNumber").val();
  			var beginTime = $("#txtStartTime").datetimebox('getValue');
  			var endTime = $("#txtEndTime").datetimebox('getValue');
  			
  			var dayOfWeek = $("input[name='qx']:checked").map(function () {
  	            return $(this).val();
  	        }).get().join(',');
  			
  			
  			var isSchedule = $("#is_schedule").is(":checked");
  			if(isSchedule){
	  			//alert(beginTime);
	  			if(beginTime == null || beginTime == ""){
	  				$.messager.alert('警告', '<p>开始时间不能为空</p>', 'warning');
	  				return false;
	  			}
	  			if(runWay != 1){
	  				if(!comptime(beginTime,endTime)){
	  					$.messager.alert('警告', '<p>结束时间要大于开始时间</p>', 'warning');
	  					return false;
	  				}
	  			}else{
	  				endTime = "";
	  			}
	  			if(runWay != 5){
	  				dayOfWeek = "";
	  			}
  			}
  			
  			/*var fileCachePath = $("#fileCachePath").val();*/
  			
  			interfaceDatasFtp = {
  				id:id,
				interfaceName:interfaceName,
	  			interfaceCode:interfaceCode,
	  			fieldId:fieldId,
	  			systemId:systemId,
	  			interfaceVersion:interfaceVersion,
	  			interfaceDes:interfaceDes,
				overTimeSetting:overTimeSetting,
				isPublic:isPublic,
				ifScheduleId:ifScheduleId,
				runWay:runWay,
				runCyc:runCyc,
				dayOfWeek:dayOfWeek,
				beginTime:beginTime,
				endTime:endTime,
				isSchedule:isSchedule,
				/*fileCachePath:fileCachePath,*/
				sourceDatas:sourceDatas,
				desDatas:desDatas,
				ftpRouteChanged:ftpRouteChanged
			}
  			
  			var fieldSystemsStr = $("#strFieldSystemsFtp").val();
  			if(fieldSystemsStr != ""){
	  			if(fieldSystemsStr.indexOf(",") != -1){
	  				interfaceDatasFtp["fieldSystemIds"] = fieldSystemsStr == ""? []:fieldSystemsStr.split(",");
	  			}else{
	  				interfaceDatasFtp["fieldSystemIds"] = [fieldSystemsStr];
	  			}
  			}else{
  				interfaceDatasFtp["fieldSystemIds"] = [];
  			}
  			
  			if(deleteHostIds != ""){
	  			if(deleteHostIds.indexOf(",") != -1){
	  				interfaceDatasFtp["deleteHostIds"] = deleteHostIds == ""?[]:deleteHostIds.split(",");
	  			}else{
	  				interfaceDatasFtp["deleteHostIds"] = [deleteHostIds];
	  			}
  			}else{
  				interfaceDatasFtp["deleteHostIds"] = []
  			}
  			return interfaceDatasFtp;
	}
	
	
	var sourceBegin = 1;
	function addSourceHost(){
		var fieldSystemElement = "<ul>"
			  + "<li>"
            + "<label for=\"sourceComboxFieldName\"  class=\"label\">所属领域：</label>"
            + "      <div class=\"input_con\">"
            + "      <input type=\"text\" name=\"sourceComboxFieldName\" class=\"sourceComboxFieldName easyui-combobox text\" tabindex=\"8\"/>"
            + "      </div>"
            + "  </li>"
            + "  <li>"
            + "      <label for=\"sourceComboxSystemName\"  class=\"label\">所属系统：</label>"
            + "      <div class=\"input_con\">"
            + "      <input type=\"text\" name=\"sourceComboxSystemName\" class=\"sourceComboxSystemName easyui-combobox text\" tabindex=\"8\"/>"
            + "      </div>"
            + "  </li>"
            + " </ul>";
          
		if(desBegin >= 2 && sourceBegin >= 1){
			$.messager.alert('警告', '<p>FTP接口暂不支持多个源对应多个目标的文件传输方式!</p>', 'warning');
			return false;
		}
		
		var sourceFieldSetVal = '<fieldset id="sourceFieldSet_' + (sourceBegin+1) + '" style="border: 1px solid #ced6db;"><legend style="margin-left: 10px;">源_' +　(sourceBegin+1) +'</legend>' + fieldSystemElement + '<div class="sourceDiv">' + $("#sourceFieldSet_" + sourceBegin + " .sourceDiv").html() + "</div></fieldset>";
		$("#sourceFieldSet_" + sourceBegin).after(sourceFieldSetVal);
		
		var isAnomous = $("#sourceFieldSet_" + sourceBegin + " .sourceAnmous").is(":checked");
		if(isAnomous){
			$(this).parent().siblings(".sourceUserInfo").css("display", "none");
			$("#sourceFieldSet_" + (sourceBegin+1) + " .sourceAnmous").attr('checked','checked');
		}else{
			$(this).parent().siblings(".sourceUserInfo").css("display", "block");
			$("#sourceFieldSet_" + (sourceBegin+1) + " .sourceAnmous").removeAttr('checked');
		}
		
		sourceBegin = sourceBegin + 1;
		if(sourceBegin > 1){
			$('#toolbarSource_del').linkbutton('enable');
		}else{
			$('#toolbarSource_del').linkbutton('disable');
		}
		//源主机所属领域
		$("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	/*var FieldName = $("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxFieldName").combobox('getData');
		    	$("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxFieldName").combobox('setValue',FieldName[0].id);*/
		    },	
		    onSelect: function(record){
		    	fieldId = $("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxFieldName").combobox('getValue');
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: fieldId},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	sourceComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	/*var SystemName = $("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxSystemName").combobox('getData');
        		    	$("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxSystemName").combobox('setValue',SystemName[0].id);*/
        		    }
                }).load();
		    }
		    
		});
		
		//源主机所属系统
		var sourceComboxSystemName = $("#sourceFieldSet_" + (sourceBegin) +  " .sourceComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
		$('#sourceHostFormFtp').data('changed',true); 
		
	}
	
	function deleteSourceHost(){
		if(sourceBegin > 1){
			var paramId = $("#sourceFieldSet_" + sourceBegin +" .sourceHostId").val();
			deleteHostIds += (deleteHostIds == ""? "":",") + paramId;
			$("#sourceFieldSet_" + sourceBegin).remove();
			sourceBegin = sourceBegin - 1;
			if(sourceBegin == 1){
				$('#toolbarSource_del').linkbutton('disable');
			}
		}else{
			
		}
		$('#sourceHostFormFtp').data('changed',true); 
	}
	
	
	var desBegin = 1;
	function addDesHost(){
		var fieldSystemElement = "<ul>"
			  + "<li>"
        + "<label for=\"desComboxFieldName\"  class=\"label\">所属领域：</label>"
        + "      <div class=\"input_con\">"
        + "      <input type=\"text\" name=\"desComboxFieldName\" class=\"desComboxFieldName easyui-combobox text\" tabindex=\"8\"/>"
        + "      </div>"
        + "  </li>"
        + "  <li>"
        + "      <label for=\"desComboxSystemName\"  class=\"label\">所属系统：</label>"
        + "      <div class=\"input_con\">"
        + "      <input type=\"text\" name=\"desComboxSystemName\" class=\"desComboxSystemName easyui-combobox text\" tabindex=\"8\"/>"
        + "      </div>"
        + "  </li>"
        + " </ul>";
		
		if(sourceBegin >= 2 && desBegin >= 1){
			$.messager.alert('警告', '<p>FTP接口暂不支持多个源对应多个目标的文件传输方式!</p>', 'warning');
			return false;
		}
		
		
		var desFieldSetVal = '<fieldset id="desFieldSet_' + (desBegin+1) + '" style="border: 1px solid #ced6db;"><legend style="margin-left: 10px;">目标_' +　(desBegin+1) +'</legend>' + fieldSystemElement + '<div class="desDiv">' + $("#desFieldSet_" + desBegin + " .desDiv").html() + "</div></fieldset>";
		$("#desFieldSet_" + desBegin).after(desFieldSetVal);
		
		var isAnomous = $("#desFieldSet_" + desBegin + " .desAnmous").is(":checked");
		if(isAnomous){
			$(this).parent().siblings(".desUserInfo").css("display", "none");
			$("#desFieldSet_" + (desBegin+1) + " .desAnmous").attr('checked','checked');
		}else{
			$(this).parent().siblings(".desUserInfo").css("display", "block");
			$("#desFieldSet_" + (desBegin+1) + " .desAnmous").removeAttr('checked');
		}
		
		desBegin = desBegin + 1;
		if(desBegin > 1){
			$('#toolbarDes_del').linkbutton('enable');
		}else{
			$('#toolbarDes_del').linkbutton('disable');
		}
		//目标主机所属领域
		$("#desFieldSet_" + (desBegin) + " .desComboxFieldName").combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllFields' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	/*var FieldName = $("#desFieldSet_" + (desBegin) + " .desComboxFieldName").combobox('getData');
		    	$("#desFieldSet_" + (desBegin) + " .desComboxFieldName").combobox('setValue',FieldName[0].id);*/
		    },	
		    onSelect: function(record){
		    	fieldId = $("#desFieldSet_" + (desBegin) +  " .desComboxFieldName").combobox('getValue');
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: fieldId},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    }
                }).load();
		    },
		    onChange: function(newValue,oldValue){
		    	desComboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: newValue},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findFieldSystemsByField' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
        		    loadFilter: function(data){
        		    	return data.content;
        		    },
        		    onLoadSuccess : function(){
        		    	/*var SystemName = $("#desFieldSet_" + (desBegin) + " .desComboxSystemName").combobox('getData');
        		    	$("#desFieldSet_" + (desBegin) + " .desComboxSystemName").combobox('setValue',SystemName[0].id);*/
        		    }
                }).load();
		    }
		    
		});
		
		
		//目标主机所属系统
		var desComboxSystemName = $("#desFieldSet_" + (desBegin) + " .desComboxSystemName").combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false
        });
		
		$('#desHostFormFtp').data('changed',true); 
	}
	
	function deleteDesHost(){
		if(desBegin > 1){
			var paramId = $("#desFieldSet_" + desBegin +" .desHostId").val();
			deleteHostIds += (deleteHostIds == ""? "":",") + paramId;
			$("#desFieldSet_" + desBegin).remove();
			desBegin = desBegin - 1;
			if(desBegin == 1){
				$('#toolbarDes_del').linkbutton('disable');
			}
			
		}else{
			
		}
		$('#desHostFormFtp').data('changed',true); 
	}
	
	$("#sourceHostFormFtp").delegate(".sourceAnmous","change", function(){
		var chooseVal = $(this).is(":checked");
		if(chooseVal){
			$(this).parent().siblings(".sourceUserInfo").css("display", "none");
			//$(".sourceUserInfo").css("display", "none");
		}else{
			$(this).parent().siblings(".sourceUserInfo").css("display", "block");
		}
	});
	
	$("#desHostFormFtp").delegate(".desAnmous","change", function(){
		var chooseVal = $(this).is(":checked");
		if(chooseVal){
			$(this).parent().siblings(".desUserInfo").css("display", "none");
		}else{
			$(this).parent().siblings(".desUserInfo").css("display", "block");
		}
	});
	
	
	//IP地址验证
	var regIP = /^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-5])))$/;
	//端口验证
	var parten = /^(\d)+$/g;
	function getSourceDatas(){
		var sourceDatas = [];
		var sourceObject = {};
		for(var i = 1; i <=　sourceBegin; i++){
			var fieldSystemId = $("#sourceFieldSet_" + i + " .sourceComboxSystemName").combobox('getValue');
			if(fieldSystemId != "")
			{
			}else
			{
				$.messager.alert('警告', '<p>源主机的所属系统不能为空!</p>', 'warning');
				return false;
			}
			var sourceHostId = $("#sourceFieldSet_" + i + " .sourceHostId").val();
			var sourceHost = $("#sourceFieldSet_" + i + " .sourceHost").val();
			if(sourceHost != "")
			{
//				if(regIP.test(sourceHost)) {
//					
//				}else{
//					$.messager.alert('警告', '<p>源主机ip地址格式不正确，请输入正确ip地址格式如：127.0.0.1 !</p>', 'warning');
//					return false;
//				}
			}else
			{
				$.messager.alert('警告', '<p>源主机不能为空!</p>', 'warning');
				return false;
			}
			var sourceHostPort = $("#sourceFieldSet_" + i + " .sourceHostPort").val();
			if(sourceHostPort != "")
			{
				if(parten.test(sourceHostPort)==true && (parseInt(sourceHostPort) <= 65535)==true && (parseInt(sourceHostPort) >= 0)==true){
				}else{
					$.messager.alert('警告', '<p>源主机端口格式不正确，请输入正确格式的端口号（0~65535）!</p>', 'warning');
					return false;
				}
				parten.lastIndex = 0;
			}else
			{
				$.messager.alert('警告', '<p>源主机端口不能为空，请输入正确格式的端口号（0~65535）!</p>', 'warning');
				return false;
			}
			var sourceIsAnmous = $("#sourceFieldSet_" + i + " .sourceAnmous").is(":checked");
			var sourceUserName = $("#sourceFieldSet_" + i + " .sourceUserName").val();
			var sourcePassword = $("#sourceFieldSet_" + i + " .sourcePassword").val();
			if(!sourceIsAnmous){
				if(sourceUserName != "")
				{
					if(sourceUserName.length > 50){
						$.messager.alert('警告', '<p>源用户名必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>源用户名不能为空!</p>', 'warning');
					return false;
				}
				
				if(sourcePassword != "")
				{
					if(sourcePassword.length > 50){
						$.messager.alert('警告', '<p>源密码必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>源密码不能为空!</p>', 'warning');
					return false;
				}
			}
			var sourceFilePath = $("#sourceFieldSet_" + i + " .sourceFilePath").val();
			var sourceIsDelFile = false;//$("#sourceFieldSet_" + i + " .sourceFileDelete").is(":checked");
			var sourcePassiveMode = $("#sourceFieldSet_" + i + " .sourcePassiveMode").is(":checked");
			var matchMode = $("#sourceFieldSet_" + i + " .matchMode option:selected").val();
			var sourceFtpServerCode = $("#sourceFieldSet_" + i + " .sourceFtpServerCode option:selected").val();
			var sourceFileName = $("#sourceFieldSet_" + i + " .sourceFileName").val();
			if(isFtpTest){
				
			}else{
				if(sourceFileName != "")
				{
					if(sourceFileName.length > 50){
						$.messager.alert('警告', '<p>文件名称必须少于50个字符!</p>', 'warning');
						return false;
					}
				}/*else
				{
					$.messager.alert('警告', '<p>文件名称不能为空!</p>', 'warning');
					return false;
				}*/
			}
			var hostType = "1";
			sourceObject = {
					fieldSystemId:fieldSystemId,
					sourceHostId:sourceHostId,
					sourceHost:sourceHost,
					sourceHostPort:sourceHostPort,
					sourceIsAnmous:sourceIsAnmous,
					sourceUserName:sourceUserName,
					sourcePassword:sourcePassword,
					sourceFilePath:sourceFilePath,
					sourceIsDelFile:sourceIsDelFile,
					sourcePassiveMode:sourcePassiveMode,
					matchMode:matchMode,
					sourceFileName:sourceFileName,
					sourceFtpServerCode:sourceFtpServerCode,
					hostType:hostType
			}
			sourceDatas.push(sourceObject);
			//alert(JSON.stringify(sourceDatas));
		}
		
		return sourceDatas;
	}
	
	
	function getDesDatas(){
		var desDatas = [];
		var desObject = {};
		for(var j = 1; j <=　desBegin; j++){
			var fieldSystemId = $("#desFieldSet_" + j + " .desComboxSystemName").combobox('getValue');
			if(fieldSystemId != "")
			{
			}else
			{
				$.messager.alert('警告', '<p>目标主机的所属系统不能为空!</p>', 'warning');
				return false;
			}
			var desHostId = $("#desFieldSet_" + j + " .desHostId").val();
			var desHost = $("#desFieldSet_" + j + " .desHost").val();
			if(desHost != "")
			{
//				if(regIP.test(desHost)) {
//					
//				}else{
//					$.messager.alert('警告', '<p>目标主机ip地址格式不正确，请输入正确ip地址格式如：127.0.0.1 !</p>', 'warning');
//					return false;
//				}
			}else
			{
				$.messager.alert('警告', '<p>目标主机不能为空!</p>', 'warning');
				return false;
			}
			var desHostPort = $("#desFieldSet_" + j + " .desHostPort").val();
			if(desHostPort != "")
			{
				if(parten.test(desHostPort) && parseInt(desHostPort) <= 65535&& parseInt(desHostPort) >= 0){
					
				}else{
					$.messager.alert('警告', '<p>目标主机端口格式不正确，请输入正确格式的端口号（0~65535）!</p>', 'warning');
					return false;
				}
				parten.lastIndex = 0;
			}else
			{
				$.messager.alert('警告', '<p>目标主机端口不能为空，请输入正确格式的端口号（0~65535）!</p>', 'warning');
				return false;
			}
			var desIsAnmous = $("#desFieldSet_" + j + " .desAnmous").is(":checked");
			var desUserName = $("#desFieldSet_" + j + " .desUserName").val();
			var desPassword = $("#desFieldSet_" + j + " .desPassword").val();
			if(!desIsAnmous){
				if(desUserName != "")
				{
					if(desUserName.length > 50){
						$.messager.alert('警告', '<p>目标用户名必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>目标用户名不能为空!</p>', 'warning');
					return false;
				}
				
				if(desPassword != "")
				{
					if(desPassword.length > 50){
						$.messager.alert('警告', '<p>目标密码必须少于50个字符!</p>', 'warning');
						return false;
					}
				}else
				{
					$.messager.alert('警告', '<p>目标密码不能为空!</p>', 'warning');
					return false;
				}
			}
			var desFilePath = $("#desFieldSet_" + j + " .desFilePath").val();
			var desIsCoverFile = $("#desFieldSet_" + j + " .desFileCover").is(":checked");
			var desPassiveMode = $("#desFieldSet_" + j + " .desPassiveMode").is(":checked");
			var desFtpServerCode = $("#desFieldSet_" + j + " .desFtpServerCode option:selected").val();
			var hostType = "2";
			desObject = {
					fieldSystemId:fieldSystemId,
					desHostId:desHostId,
					desHost:desHost,
					desHostPort:desHostPort,
					desIsAnmous:desIsAnmous,
					desUserName:desUserName,
					desPassword:desPassword,
					desFilePath:desFilePath,
					desIsCoverFile:desIsCoverFile,
					desPassiveMode:desPassiveMode,
					desFtpServerCode:desFtpServerCode,
					hostType:hostType
			}
			desDatas.push(desObject);
		}
		
		return desDatas;
	}
	
	var sourceDataBack = 1;
	var desDataBack = 1;
	function FtpUpdate(row){
		for(var i = sourceDataBack - 1; i >　1; i--){
			$("#sourceFieldSet_" + i).remove();
			sourceBegin = sourceBegin - 1;
		}
		
		for(var j = desDataBack - 1; j >　1; j--){
			$("#desFieldSet_" + j).remove();
			desBegin = desBegin - 1;
		}
		deleteHostIds = "";
		var jsonData = {
				id:row.interfaceId
			}
			/* 根据接口id获取接口信息进行表单回显  */
			$.ajax({
	  			type: "get",
	  			url: BASE_URL_HTTP_INTERFACE + '/findIfByIdFtp' + '?v=' + Math.random(),
	  			dataType:'json',
	  			data: jsonData,
	  			contentType:"application/json",
	  			success: function(result) {
	  				if(result != null){
	  					$("#interfaceNameFtp").val(result.interfaceName).validatebox('validate');
	  					$("#interfaceCodeFtp").val(result.interfacecode).validatebox('validate');
	  					$("#comboxFieldNameFtp").combobox("setValue", result.filedId);
	  					$("#comboxSystemNameFtp").combobox("setValue", result.filedSystemId);
	  					$("#interfaceVserionFtp").val(result.version);
	  					$("#overTimeSettingFtp").val(result.overtime).validatebox('validate');
	  					$("#comboxIsPublicFtp").combobox("setValue", result.ifPublic);
	  					var chooseVal = $("#comboxIsPublicFtp").combobox('getValue');
	  			    	if(chooseVal=="0"){
	  			    		$("#li_visibleFtp").css("display","block");
	  			    	}else{
	  			    		$("#li_visibleFtp").css("display","none");
	  			    	}
	  			    	
	  					$("#interfaceDescriptionsFtp").val(result.desc);
	  					
	  					/*$("#fileCachePath").val(result.fileCachePath);*/
	  					
	  					reBackDataFtp(row, result.visibleFieldSystems);
	  					/*reBackHostData(row, result.ftpServerSourceDatas, result.ftpServerDesDatas);*/
	  					if(result.isSchedule == "0"){
	  						//非调度
	  						$("#is_schedule").attr('checked',false);
	  						$(".sheduleTrigger").hide();
	  						$(".externalTrigger").show();
	  						$('input[name=qx]').attr('checked',true);
	  						$('#txtStartTime').datetimebox('setValue', Date.parse(new Date()).toString());
	  						setTimeout(function(){
	  							$("#txtStartTime").siblings(".textbox").children(".textbox-text").val($("#txtStartTime").combobox('getText'));
	  						},50);
	  						
	  						$('#txtEndTime').datetimebox('setValue', '2020-01-01 00:00:00');
	  						setTimeout(function(){
	  							$("#txtEndTime").siblings(".textbox").children(".textbox-text").val($("#txtEndTime").combobox('getText'));
	  						},50);
	  						$("#requestTriggerAddress").val(result.routePublishUrl);
	  					}else{
	  						//调度
	  						$("#is_schedule").attr('checked',true);
	  						$(".sheduleTrigger").show();
	  						$(".externalTrigger").hide();
	  						reBackIfSchedule(row, result.ifSchedules);
	  					}
	  					
	  					sourceDataBack = 1;
	  					desDataBack = 1;
	  					for(var k = 0; k < result.ftpServerSourceDatas.length; k++){
	  							if(sourceDataBack == 1){
	  								$("#sourceFieldSet_1 .sourceHostId").val(result.ftpServerSourceDatas[k].ftpServerId);
	  								//alert("k:" + k + " fieldId:" + result.ftpServerSourceDatas[k].fieldId + " fieldSystemId:" + result.ftpServerSourceDatas[k].fieldSystemId);
	  								$("#sourceFieldSet_1 .sourceComboxFieldName").combobox('setValue', result.ftpServerSourceDatas[k].fieldId);
	  								$("#sourceFieldSet_1 .sourceComboxSystemName").combobox('setValue', result.ftpServerSourceDatas[k].fieldSystemId);
	  								$("#sourceFieldSet_1 .matchMode option[value=" +result.ftpServerSourceDatas[k].matchMode +"]").attr("selected",true);
	  								$("#sourceFieldSet_1 .sourceFileName").val(result.ftpServerSourceDatas[k].fileName);
		  							$("#sourceFieldSet_1 .sourceHost").val(result.ftpServerSourceDatas[k].host);
		  							$("#sourceFieldSet_1 .sourceHostPort").val(result.ftpServerSourceDatas[k].port);
		  							if(result.ftpServerSourceDatas[k].ifAnonymous == "0"){
		  								$("#sourceFieldSet_1 .sourceAnmous").removeAttr('checked');
		  								$("#sourceFieldSet_1 .sourceUserInfo").css("display", "block");
		  								$("#sourceFieldSet_1 .sourceUserName").val(result.ftpServerSourceDatas[k].userName);
			  							$("#sourceFieldSet_1 .sourcePassword").val(result.ftpServerSourceDatas[k].password);
		  							}else if(result.ftpServerSourceDatas[k].ifAnonymous == "1"){
		  								$("#sourceFieldSet_1 .sourceAnmous").attr('checked','checked');
		  								$("#sourceFieldSet_1 .sourceUserInfo").css("display", "none");
		  							}else{
		  								
		  							}
		  							if(result.ftpServerSourceDatas[k].ifDelSource == "0"){
		  								$("#sourceFieldSet_1 .sourceFileDelete").removeAttr('checked');
		  							}else if(result.ftpServerSourceDatas[k].ifDelSource == "1"){
		  								$("#sourceFieldSet_1 .sourceFileDelete").attr('checked','checked');
		  							}
		  							
		  							$("#sourceFieldSet_1 .sourceFileDelete").val();
		  							
		  							if(result.ftpServerSourceDatas[k].passiveMode == "0"){
		  								$("#sourceFieldSet_1 .sourcePassiveMode").removeAttr('checked');
		  							}else if(result.ftpServerSourceDatas[k].passiveMode == "1"){
		  								$("#sourceFieldSet_1 .sourcePassiveMode").attr('checked','checked');
		  							}
		  							
		  							$("#sourceFieldSet_1 .sourcePassiveMode").val();
		  							
		  							
		  							$("#sourceFieldSet_1 .sourceFilePath").val(result.ftpServerSourceDatas[k].fileDir);
		  							$("#sourceFieldSet_1 .sourceFtpServerCode option[value=" +result.ftpServerSourceDatas[k].serverCode +"]").attr("selected",true);
		  							sourceDataBack = sourceDataBack + 1;
	  							}else{
	  								addSourceHost();
	  								$("#sourceFieldSet_" +(k+1)+" .sourceHostId").val(result.ftpServerSourceDatas[k].ftpServerId);
	  								//alert("k:" + k + "fieldId:" + result.ftpServerSourceDatas[k].fieldId + "fieldSystemId:" + result.ftpServerSourceDatas[k].fieldSystemId);
	  								$("#sourceFieldSet_" +(k+1)+" .sourceComboxFieldName").combobox('setValue', result.ftpServerSourceDatas[k].fieldId);
	  								$("#sourceFieldSet_" +(k+1)+" .sourceComboxSystemName").combobox('setValue', result.ftpServerSourceDatas[k].fieldSystemId);
	  								$("#sourceFieldSet_" +(k+1)+" .matchMode option[value=" +result.ftpServerSourceDatas[k].matchMode +"]").attr("selected",true);
	  								$("#sourceFieldSet_" +(k+1)+" .sourceFileName").val(result.ftpServerSourceDatas[k].fileName);
	  								$("#sourceFieldSet_" +(k+1)+" .sourceHost").val(result.ftpServerSourceDatas[k].host);
		  							$("#sourceFieldSet_" +(k+1)+ " .sourceHostPort").val(result.ftpServerSourceDatas[k].port);
		  							
		  							if(result.ftpServerSourceDatas[k].ifAnonymous == "0"){
		  								$("#sourceFieldSet_" +(k+1)+ " .sourceAnmous").removeAttr('checked');
		  								$("#sourceFieldSet_" +(k+1)+ " .sourceUserInfo").css("display", "block");
		  								$("#sourceFieldSet_" +(k+1)+ " .sourceUserName").val(result.ftpServerSourceDatas[k].userName);
			  							$("#sourceFieldSet_" +(k+1)+ " .sourcePassword").val(result.ftpServerSourceDatas[k].password);
		  							}else if(result.ftpServerSourceDatas[k].ifAnonymous == "1"){
		  								$("#sourceFieldSet_" +(k+1)+ " .sourceAnmous").attr('checked','checked');
		  								$("#sourceFieldSet_" +(k+1)+ " .sourceUserInfo").css("display", "none");
		  							}else{
		  								
		  							}
		  							
		  							if(result.ftpServerSourceDatas[k].ifDelSource == "0"){
		  								$("#sourceFieldSet_" +(k+1)+ " .sourceFileDelete").removeAttr('checked');
		  							}else if(result.ftpServerSourceDatas[k].ifDelSource == "1"){
		  								$("#sourceFieldSet_" +(k+1)+ " .sourceFileDelete").attr('checked','checked');
		  							}
		  							
		  							if(result.ftpServerSourceDatas[k].passiveMode == "0"){
		  								$("#sourceFieldSet_" +(k+1)+ " .sourcePassiveMode").removeAttr('checked');
		  							}else if(result.ftpServerSourceDatas[k].passiveMode == "1"){
		  								$("#sourceFieldSet_" +(k+1)+ " .sourcePassiveMode").attr('checked','checked');
		  							}
		  							
		  							
		  							$("#sourceFieldSet_" +(k+1)+ " .sourceFilePath").val(result.ftpServerSourceDatas[k].fileDir);
		  							$("#sourceFieldSet_" +(k+1)+ " .sourceFtpServerCode option[value=" +result.ftpServerSourceDatas[k].serverCode +"]").attr("selected",true);
		  							sourceDataBack = sourceDataBack + 1;
	  							}
	  					}
	  					for(var l = 0; l < result.ftpServerDesDatas.length; l++){		
	  							
	  							if(desDataBack == 1){
	  								$("#desFieldSet_1 .desHostId").val(result.ftpServerDesDatas[l].ftpServerId);
	  								//alert("l:" + l + "fieldId:" + result.ftpServerDesDatas[l].fieldId + "fieldSystemId:" + result.ftpServerDesDatas[l].fieldSystemId);
	  								$("#desFieldSet_1 .desComboxFieldName").combobox('select', result.ftpServerDesDatas[l].fieldId);
	  								
	  								setTimeout(function(){},2000);
	  								/*setTimeout(function(){
	  									alert('setValue');*/
	  									$("#desFieldSet_1 .desComboxSystemName").combobox('setValue', result.ftpServerDesDatas[l].fieldSystemId);
	  								/*},5000);*/
		  							$("#desFieldSet_1 .desHost").val(result.ftpServerDesDatas[l].host);
		  							$("#desFieldSet_1 .desHostPort").val(result.ftpServerDesDatas[l].port);
		  							
		  							if(result.ftpServerDesDatas[l].ifAnonymous == "0"){
		  								$("#desFieldSet_1 .desAnmous").removeAttr('checked');
		  								$("#desFieldSet_1 .desUserInfo").css("display", "block");
		  								$("#desFieldSet_1 .desUserName").val(result.ftpServerDesDatas[l].userName);
			  							$("#desFieldSet_1 .desPassword").val(result.ftpServerDesDatas[l].password);
		  							}else if(result.ftpServerDesDatas[l].ifAnonymous == "1"){
		  								$("#desFieldSet_1 .desAnmous").attr('checked','checked');
		  								$("#desFieldSet_1 .desUserInfo").css("display", "none");
		  							}else{
		  								
		  							}
		  							
		  							if(result.ftpServerDesDatas[l].ifCover == "0"){
		  								$("#desFieldSet_1 .desFileCover").removeAttr('checked');
		  							}else if(result.ftpServerDesDatas[l].ifCover == "1"){
		  								$("#desFieldSet_1 .desFileCover").attr('checked','checked');
		  							}
		  							
		  							if(result.ftpServerDesDatas[l].passiveMode == "0"){
		  								$("#desFieldSet_1 .desPassiveMode").removeAttr('checked');
		  							}else if(result.ftpServerDesDatas[l].passiveMode == "1"){
		  								$("#desFieldSet_1 .desPassiveMode").attr('checked','checked');
		  							}
		  							
		  							
		  							$("#desFieldSet_1 .desFilePath").val(result.ftpServerDesDatas[l].fileDir);
		  							$("#desFieldSet_1 .desFtpServerCode option[value=" +result.ftpServerDesDatas[l].serverCode +"]").attr("selected",true);
		  							desDataBack = desDataBack + 1;
	  							}else{
	  								addDesHost();
	  								$("#desFieldSet_" +(l+1)+ " .desHostId").val(result.ftpServerDesDatas[l].ftpServerId);
	  								//alert("l:" + l + "fieldId:" + result.ftpServerDesDatas[l].fieldId + "fieldSystemId:" + result.ftpServerDesDatas[l].fieldSystemId);
	  								setTimeout(function(){},2000);
	  								$("#desFieldSet_" +(l+1)+ " .desComboxFieldName").combobox('select', result.ftpServerDesDatas[l].fieldId);
	  								$("#desFieldSet_" +(l+1)+ " .desComboxSystemName").combobox('setValue', result.ftpServerDesDatas[l].fieldSystemId);
	  								$("#desFieldSet_" +(l+1)+ " .desHost").val(result.ftpServerDesDatas[l].host);
		  							$("#desFieldSet_" +(l+1)+ " .desHostPort").val(result.ftpServerDesDatas[l].port);
		  							
		  							if(result.ftpServerDesDatas[l].ifAnonymous == "0"){
		  								$("#desFieldSet_" +(l+1)+ " .desAnmous").removeAttr('checked');
		  								$("#desFieldSet_" +(l+1)+ " .desUserInfo").css("display", "block");
		  								$("#desFieldSet_" +(l+1)+ " .desUserName").val(result.ftpServerDesDatas[l].userName);
			  							$("#desFieldSet_" +(l+1)+ " .desPassword").val(result.ftpServerDesDatas[l].password);
		  							}else if(result.ftpServerDesDatas[l].ifAnonymous == "1"){
		  								$("#desFieldSet_" +(l+1)+ " .desAnmous").attr('checked','checked');
		  								$("#desFieldSet_" +(l+1)+ " .desUserInfo").css("display", "none");
		  							}else{
		  								
		  							}
		  							
		  							if(result.ftpServerDesDatas[l].ifCover == "0"){
		  								$("#desFieldSet_" +(l+1)+ " .desFileCover").removeAttr('checked');
		  							}else if(result.ftpServerDesDatas[l].ifCover == "1"){
		  								$("#desFieldSet_" +(l+1)+ " .desFileCover").attr('checked','checked');
		  							}
		  							
		  							if(result.ftpServerDesDatas[l].passiveMode == "0"){
		  								$("#desFieldSet_" +(l+1)+ " .desPassiveMode").removeAttr('checked');
		  							}else if(result.ftpServerDesDatas[l].passiveMode == "1"){
		  								$("#desFieldSet_" +(l+1)+ " .desPassiveMode").attr('checked','checked');
		  							}
		  							
		  							$("#desFieldSet_" +(l+1)+ " .desFilePath").val(result.ftpServerDesDatas[l].fileDir);
		  							$("#desFieldSet_" +(l+1)+ " .desFtpServerCode option[value=" +result.ftpServerDesDatas[l].serverCode +"]").attr("selected",true);
		  							desDataBack = desDataBack + 1;
	  							}
	  					}
	  					//$("#sourceFieldSet_2 .sourceHost").val("sdfsdlfjs");
	  					$("#winFtp").window('setTitle', result.interfaceName + '-修改');
	  					
	  				}
	  				
	  				$('#sourceHostFormFtp').data('changed',false); 
	  				$('#desHostFormFtp').data('changed',false); 
	  				$('#limitFormFtp').data('changed',false); 
	  			},
	  			error: function() {
	  				$('#sourceHostFormFtp').data('changed',false);
	  				$.messager.alert('错误','<p>服务异常，操作失败，请稍后重试或联系管理员!</p>', 'error');
	  			}
	  		});
		$('#winFtp').window('open');
	}
	

	
	/* 树 */
	//点击分配打开用户授权修改页面
	function onOpenEditFtp(rowIndex) {
		var rowData = $('#datagrid').datagrid('getRows')[parseInt(rowIndex, 10)];
		$.ajax({
			type: "get",
			url: BASE_URL_HTTP_INTERFACE + "/getFieldSystemRoot?id="+rowData.id,
			dataType:"json",/* 
			async:false, */
			contentType: "application/json",
			success: function(data) {
				//fieldSystems = data;
				reBackDataFtp(rowData,data);
			},
			error: function() {
				$.messager.alert('错误','<p>服务异常，修改用户授权信息失败，请稍后重试!</p>','error');
			}
		});	
		
	}
	
	//点击分配后要回显用户相关数据
	function reBackDataFtp(rowData,data){
		var systemsInfo = getSystemsStrFromSyslistFtp(data);
		g_currSystemsStr = systemsInfo.names;
		$("#strFieldSystemsFtp").val(systemsInfo.ids);
		$("#systemFtp").val(systemsInfo.names);
	}
	
	
	
	function reBackIfSchedule(rowData, ifSchedules){
		for(var i = 0, len=ifSchedules.length; i < len; ++i)
		{
			$("#ifScheduleId").val(ifSchedules[i].ifscheduleId);
			$("#txtStartTime").datetimebox('setValue',ifSchedules[i].beginTime);
			$("#txtEndTime").datetimebox('setValue',ifSchedules[i].endTime);
			$("#comboxExecutionCycleTime").combobox('setValue',ifSchedules[i].runWay);
			$("#txtExecutionCycleNumber").val(ifSchedules[i].runCyc);
			var chooseVal = ifSchedules[i].runWay;
			var cycleNum = ifSchedules[i].runCyc;
			if(chooseVal == "5" && cycleNum == "1")
			{
				$(".daySel").show();
			}else{
				$(".daySel").hide();
			}
			
			var dayOfWeek = ifSchedules[i].dayOfWeek;
			if(dayOfWeek == "" || dayOfWeek == null){
				
			}else{
				if(dayOfWeek.indexOf(",") != -1){
					var dayOfWeekCheck = dayOfWeek.split(',');
					for(var j = 0;j < dayOfWeekCheck.length;j++){
						$("input:checkbox[value='" + dayOfWeekCheck[j] + "']").attr('checked','true');
					}
				}else{
					$("input:checkbox[value='" + dayOfWeek + "']").attr('checked','true');
				}
			}
			/*$("#fileCachePath").val(ifSchedules[i].fileCachePath);*/
		}
	}
	
	//通过领域系统对象数组转成系统字符串
	function getSystemsStrFromSyslistFtp(fieldSystemsArr) {
		var systemsStr = "";
		var systemIdsStr = "";
		for(var i = 0, len=fieldSystemsArr.length; i < len; ++i)
		{
			if(!fieldSystemsArr[i])
			{
				continue;
			}
			var fieldName = fieldSystemsArr[i].fieldName;
			var systemName = fieldSystemsArr[i].fieldSystemName;
			systemIdsStr += (systemIdsStr == ""? "":",") + fieldSystemsArr[i].fieldSystemId;
			systemsStr += systemName + (i == len-1? "":",");
		}
		return {
			ids:systemIdsStr,
			names:systemsStr
		};
	}
	
	//通过字符串获取系统列表
	function getSystemListFromStrFtp(fieldSystemsStr) {
		if(!fieldSystemsStr)
		{
			return [];
		}
		var fieldSystemList = fieldSystemsStr.split(",");
		var systemList = [];
		for(var i = 0, len=fieldSystemList.length; i < len; ++i)
		{
			if(!fieldSystemList[i])
			{
				continue;
			}
			var systemName = fieldSystemList[i].split("-")[1];
			if(systemName)
			{
				systemList.push(systemName);
			}
		}
		return systemList;
	}

	//通过字符串获取构造领域系统的树节点信息
	function getFieldSystemNodesFromStrFtp(fieldSystemsStr) {
		if(!fieldSystemsStr)
		{
			return [];
		}
		var fieldSystemList = fieldSystemsStr.split(",");
		var fieldList = [];
		var systemNodeList = [];
		for(var i = 0, len=fieldSystemList.length; i < len; ++i)
		{
			if(!fieldSystemList[i])
			{
				continue;
			}
			var fieldName = fieldSystemList[i].split("-")[0];
			var systemName = fieldSystemList[i].split("-")[1];
			if(fieldName)
			{
				var tempNode = {};
				var j = 0;
				for(; j < fieldList.length; ++j)
				{
					if(fieldList[j].text == fieldName)
					{
						if(systemName)
						{
							fieldList[j].children.push({
								text:systemName,
								children:[],
								nodeType:"fieldSystem"
							});
						}
						break;
					}
				}
				if(j == fieldList.length)
				{
					tempNode.text = fieldName;
					tempNode.nodeType = "field";
					tempNode.children = [];
					if(systemName)
					{
						tempNode.children.push({
							text:systemName,
							children:[],
							nodeType:"fieldSystem"
						});
					}
					fieldList.push(tempNode);
				}
			}
			
		}
		return fieldList;
	}
	
	//通过领域系统对象数组转换成树节点信息
	function getFieldSystemNodesFromArrFtp(fieldSystemsArr) {
		if(!fieldSystemsArr)
		{
			return [];
		}
		var fieldNodes = [];
		for(var i = 0, len=fieldSystemsArr.length; i < len; ++i)
		{
			if(!fieldSystemsArr[i])
			{
				continue;
			}
			var fieldName = fieldSystemsArr[i].fieldName;
			var systemName = fieldSystemsArr[i].fieldSystemName;
			if(fieldName)
			{
				var tempNode = {};
				var j = 0;
				for(; j < fieldNodes.length; ++j)
				{
					if(fieldNodes[j].text == fieldName)
					{
						if(systemName)
						{
							fieldNodes[j].children.push({
								text:systemName,
								children:[],
								nodeType:"fieldSystem"
							});
						}
						break;
					}
				}
				if(j == fieldNodes.length)
				{
					tempNode.text = fieldName;
					tempNode.nodeType = "field";
					tempNode.children = [];
					if(systemName)
					{
						tempNode.children.push({
							text:systemName,
							children:[],
							nodeType:"fieldSystem"
						});
					}
					fieldNodes.push(tempNode);
				}
			}
		}
		return fieldNodes;
	}
	
	//显示所属系统
	function onShowDetailFtp(rowIndex) {
		var rowData = $('#datagrid').datagrid('getRows')[parseInt(rowIndex, 10)];
		$.ajax({
			type: "get",
			url: BASE_URL_USER_SEARCH + "/getFieldSystemRoot?id="+rowData.id,
			dataType:"json",
			contentType: "application/json",
			success: function(data) {
				//fieldSystems = data;
				
				var fieldSystemsNodes = getFieldSystemNodesFromArrFtp(data);
				$("#sys_show_tt").tree("loadData", fieldSystemsNodes);
				$("#sys_show_tt > li > ul > li > .tree-node > .tree-file").css("background","url('../../images/st_folder.png') no-repeat 2px 2px");
				$("#system_show").window('setTitle',rowData.userCode + '所属系统');
				$('#system_show').window('open');
			},
			error: function() {
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
				$.messager.alert('错误','<p>服务异常，修改用户授权信息失败，请稍后重试!</p>','error');
			}
		});		
	}
	
	
	function setCheckedFtp(sysName) {
		if(!sysName)
		{
			return;
		}
		$("#ttFtp li .tree-node").each(function(){
			if($(".tree-title", $(this)).text() == sysName)
			{
				$('#ttFtp').tree('check', this);
				return false;
			}
		});
		
	}
	
	function setCheckedListFtp(sysNameArr)
	{
		if(sysNameArr && sysNameArr.length)
		{
			for(var i = 0, len = sysNameArr.length; i < len; ++i)
			{
				setCheckedFtp(sysNameArr[i]);
			}
		}
	}
	
	function reSetTreeFtp(){
		$('#system_selectionFtp').window('open');	
		var txtInterface = $("#systemFtp").val().split(",")[0];
		if(txtInterface !== '')
		{
			$("#systemNameFtp").val(txtInterface);
			choose_treeFtp();
		}
		else
		{
			$("#systemNameFtp").val('');
			$(".tree_conFtp").scrollTop(0);
			var row = $('#ttFtp li .tree-node');  
			row.removeClass('tree-node-selected');
		}
		
		var checkedNodes = $("#ttFtp").tree("getChecked");
		if(checkedNodes)
		{
			$.each(checkedNodes, function(index, node) {
				$("#ttFtp").tree("uncheck", node.target);
			});
		}
		
		var currSystemsStr = $("#systemFtp").val();
		if(currSystemsStr != '')
		{
			setCheckedListFtp(currSystemsStr.split(","));
		}
	}
	
	
	function choose_treeFtp()
	{
		$('#ttFtp').tree('expandAll');
		if(arrayLiFtp.length == 0 && arrayLiIndFtp == 0)
		{
			var searchVal = $("#systemNameFtp").val().toUpperCase(); 
			var row = $('#ttFtp li .tree-node');  
			var rowcolumn = $('#ttFtp li .tree-node > .tree-title');  
			var i = 0, j = 0;
			var offsetC = 0
			row.removeClass('tree-node-selected');  
			rowcolumn.each(function (column) {  
				var matchVal = $(this).text(); 
				if(matchVal.indexOf(searchVal) != -1)
				{
					i++;
					var panel_top = parseInt($(this).parents(".panel").css("top"), 10);
					
					if(i <= 1)
					{
						$(this).parent().addClass('tree-node-selected'); 
						var top = $(".tree_conFtp").scrollTop() + $(this).offset().top - 76 - panel_top;
						$(".tree_conFtp").scrollTop(top);
						arrayLiIndFtp = 1;
					}			
					arrayLiFtp.push([matchVal,$(".tree_conFtp").scrollTop() + $(this).offset().top - 76 - panel_top]);
					
				}
				}); 
			}else
			{
				var rowcolumn = $('#ttFtp li .tree-node > .tree-title'); 
				var row = $('#ttFtp li .tree-node');  
				row.removeClass('tree-node-selected');
				
				if(arrayLiIndFtp <  arrayLiFtp.length)
				{
					rowcolumn.each(function (column) {  
						var matchVal = $(this).text(); 
						if(matchVal == arrayLiFtp[arrayLiIndFtp][0])
						{
							$(this).parent().addClass('tree-node-selected'); 
							$(".tree_conFtp").scrollTop(arrayLiFtp[arrayLiIndFtp][1]);
							arrayLiIndFtp++;
							return false;
						}
					});
				}else
				{
					//arrayLi = [];
					arrayLiIndFtp = 0;
					$(".tree_conFtp").scrollTop(0);
					choose_treeFtp();
				}
			}
	}
	
	
	/* 树 */
	
	
	// 测试源ftp服务器是否可连接
	function testSourceFtpServer(){
		isFtpTest = true;
		var sourceDatas =  getSourceDatas();
		if(sourceDatas == false){
			return false;
		}
		var jsonData = {
			hostDatas:sourceDatas
		};
		$("#progressbar3, #progressbar_tips3").fadeIn();
		loading_point.timer = setInterval(loading3,200);
	  	$.ajax({
	  		type: "post",
	  		url: BASE_URL_HTTP_INTERFACE + '/testFtpServer' + '?v=' + Math.random(),
	  		dataType:'json',
	  		data: JSON.stringify(jsonData),
	  		contentType:"application/json",
	  		success: function(result) {
	  			$("#progressbar3, #progressbar_tips3").fadeOut();
				clearInterval(loading_point.timer);
	  			if(result.backValue == true){
	  				$.messager.alert('提示','<p>测试成功!</p>', 'info');
	  			}else if(result.backValue == false){
	  				$.messager.alert('错误','<p>' + result.errorDes + '!</p>', 'error');
	  			}	
	  		},
	  		error: function() {
	  			$("#progressbar3, #progressbar_tips3").fadeOut();
				clearInterval(loading_point.timer);
	  			$.messager.alert('错误','<p>服务异常，测试失败，请稍后重试或联系管理员!</p>', 'error');
	  		}
	  	});
	}
	
	//测试目标ftp服务器是否可连接
	function testDesFtpServer(){
		var desDatas =  getDesDatas();
		if(desDatas == false){
			return false;
		}
		
		var jsonData = {
			hostDatas:desDatas
		};
		$("#progressbar3, #progressbar_tips3").fadeIn();
		loading_point.timer = setInterval(loading3,200);
	  	$.ajax({
	  		type: "post",
	  		url: BASE_URL_HTTP_INTERFACE + '/testFtpServer' + '?v=' + Math.random(),
	  		dataType:'json',
	  		data: JSON.stringify(jsonData),
	  		contentType:"application/json",
	  		success: function(result) {
	  			$("#progressbar3, #progressbar_tips3").fadeOut();
				clearInterval(loading_point.timer);
	  			if(result.backValue == true){
	  				$.messager.alert('提示','<p>测试成功!</p>', 'info');
	  			}else if(result.backValue == false){
	  				$.messager.alert('错误','<p>' + result.errorDes + '!</p>', 'error');
	  			}	
	  		},
	  		error: function() {
	  			$("#progressbar3, #progressbar_tips3").fadeOut();
				clearInterval(loading_point.timer);
	  			$.messager.alert('错误','<p>服务异常，测试失败，请稍后重试或联系管理员!</p>', 'error');
	  		}
	  	});
	}
	
	$("#is_schedule").change(function(){
		var chooseVal = $("#is_schedule").is(":checked");
		if(chooseVal){
			$(".sheduleTrigger").show();
			$(".externalTrigger").hide();
		}else{
			var interfaceCode = $("#interfaceCodeFtp").val();
			var systemId = $("#comboxSystemNameFtp").combobox("getValue");
			var interfaceVersion = $.trim($("#interfaceVserionFtp").val());
			
			$.ajax({
		  		type: "get",
		  		url: BASE_URL_HTTP_INTERFACE + '/getRequestAddress' + '?interfaceCode=' + interfaceCode + '&systemId=' + systemId + '&interfaceVersion=' + interfaceVersion + '&v=' + Math.random(),
		  		dataType:'json',
		  		contentType:"application/json",
		  		success: function(result) {
		  			$("#requestTriggerAddress").val(result.routePublishUrl);
		  		},
		  		error: function() {
		  			$.messager.alert('错误','<p>服务异常，获取调用地址失败，请稍后重试或联系管理员!</p>', 'error');
		  		}
		  	});
			$(".sheduleTrigger").hide();
			$(".externalTrigger").show();
		}
	});
	
	
	